package com.adee.netty.groupchat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.SimpleDateFormat;
import java.util.Date;

public class GroupChatServerHandler extends SimpleChannelInboundHandler<String> {
    // 定义一个channel组，管理所有的channel，线程安全的
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    // 连接建立
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        // 广播消息到channelGroup当前所有channel中
        channelGroup.writeAndFlush("[客户端]" + channel.remoteAddress() + " 加入聊天" + fmt.format(new Date()) + "\n");
        channelGroup.add(channel);
    }
    // 断开连接
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        // 当前channel自动从channelGroup中删除，不用调用channelGroup.remove(channel)
        channelGroup.writeAndFlush("[客户端]" + ctx.channel().remoteAddress() + " 离开了\n");
        System.out.println("当前channelGroup大小：" + channelGroup.size());
    }

    // 表示channel处于活动状态，提示xx上线
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + " 上线了~");
    }
    // channel处于非活动状态
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + " 离线了~");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Channel channel = ctx.channel();
        System.out.println(msg);
        channelGroup.forEach(ch -> {
            if(channel != ch) {
                ch.writeAndFlush("[客户]" + channel.remoteAddress() + ":" + msg + "\n");
            } else {
                ch.writeAndFlush("[自己] " + msg + "\n");
            }
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 关闭通道
        System.out.println("遇到异常，关闭连接");
        cause.printStackTrace();
        ctx.channel().close();
    }
}
